package com.hqd.ch03.v28.factory.support;

import com.hqd.ch03.v28.beans.Mergeable;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

public class ManagedSet<E> extends LinkedHashSet<E> implements Mergeable {


    private String elementTypeName;

    private boolean mergeEnabled;


    public ManagedSet() {
    }

    public ManagedSet(int initialCapacity) {
        super(initialCapacity);
    }


    @SafeVarargs
    public static <E> ManagedSet<E> of(E... elements) {
        ManagedSet<E> set = new ManagedSet<>();
        Collections.addAll(set, elements);
        return set;
    }


    public String getElementTypeName() {
        return this.elementTypeName;
    }

    public void setElementTypeName(String elementTypeName) {
        this.elementTypeName = elementTypeName;
    }

    @Override
    public boolean isMergeEnabled() {
        return this.mergeEnabled;
    }

    public void setMergeEnabled(boolean mergeEnabled) {
        this.mergeEnabled = mergeEnabled;
    }

    @Override
    public Set<E> merge(Object parent) {
        if (!this.mergeEnabled) {
            throw new IllegalStateException("Not allowed to merge when the 'mergeEnabled' property is set to 'false'");
        }
        if (parent == null) {
            return this;
        }
        if (!(parent instanceof Set)) {
            throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]");
        }
        Set<E> merged = new ManagedSet<>();
        merged.addAll((Set<E>) parent);
        merged.addAll(this);
        return merged;
    }

}
